package top.ywlog.permission.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.ywlog.permission.model.Mail;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;


/**
 * @author Durian
 */
@Slf4j
@Service
@EnableAsync
public class MailService
{
    @Resource
    private JavaMailSender javaMailSender;
    //template模板引擎
    @Resource
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Async
    public void sendTemplateMail(Mail mail)
    {
        try
        {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);// 发送人的邮箱
            messageHelper.setTo(mail.getEmail());//发给谁  对方邮箱
            messageHelper.setSubject(mail.getTitle()); //标题
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            context.setVariables(mail.getAttachment());
            //获取thymeleaf的html模板
            //指定模板路径
            String emailContent = templateEngine.process("/MailTemplate", context);
            messageHelper.setText(emailContent, true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (Exception e)
        {
            log.error("模板邮件发送失败:{}", e.getMessage());
            log.error("邮箱为{}的用户发送密码邮件失败，该用户初始密码是{}, 失败原因是{}", mail.getEmail(),
                    mail.getAttachment().get("password"), e.getMessage());
        }
    }

}
